package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.adapter.ImageFileAdapter;
import com.tangkun.environment.entity.base.CommonReturn;
import com.tangkun.environment.entity.personcenter.UploadResourceReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.SquareGridView;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 咨询  创建咨询
 */
public class ZiXunAddActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.tv_zixun_fenlei)
    TextView tvZixunFenlei;
    @BindView(R.id.ll_zixun_fenlei)
    LinearLayout llZixunFenlei;
    @BindView(R.id.et_zixun_neirong)
    EditText etZixunNeirong;
    @BindView(R.id.squareGridView)
    SquareGridView squareGridView;
    private Context mContext;

    /**
     * 选中咨询分类ID
     */
    private String selectedIds = "";
    /**
     * 选中咨询分类名字
     */
    private String selectedName = "";
    /**
     * 图片半路径地址，以逗号隔开
     */
    private String img = "";

    /**
     * 图片列表适配器
     */
    private ImageFileAdapter adapter;

    // 最大图片上传张数
    private static final int IMAGE_NUM = 9;
    private static final int IMAGE_W = 400;
    private static final int IMAGE_H = 200;
    private static final int CAPTURE_IMAGE = 1;

    /**
     * 是否已经提交过数据了,避免重复网络请求
     */
    private boolean hasPosted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zixun);
        mContext = this;
        ButterKnife.bind(this);
        title.setText("咨询");
        next.setText("确认");
        initView();
    }

    private void initView() {
        adapter = new ImageFileAdapter(this, R.layout.weibo_pic_list);
//        adapter.setCanDelete(true);
        adapter.setShowOriginal(false);//不显示原图
        adapter.getFileList();// initialize fileList
        Utils.setGridViewHeightBasedOnChildren(squareGridView, 3);
        // adapter.setShowOriginal(false);
        squareGridView.setAdapter(adapter);
    }

    @OnClick({R.id.back, R.id.next, R.id.ll_zixun_fenlei})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                Utils.hideSoftKeyboard(ZiXunAddActivity.this, back);
                JumpHelper.finish(mContext);
                break;
            case R.id.next://确认
                queding();
                break;
            case R.id.ll_zixun_fenlei://分类
                Intent modifyInfectionIntent1 = new Intent(ZiXunAddActivity.this, ZiXunFeiLeiActivity.class);
                modifyInfectionIntent1.putExtra("selectedIds", selectedIds);//选中ID
                JumpHelper.jumpForResult(ZiXunAddActivity.this, modifyInfectionIntent1, 1000, false);
                break;
        }
    }

    /**
     * 确定
     */
    private void queding() {
        if (TextUtils.isEmpty(selectedIds)) {
            showToast("请选择咨询分类");
            return;
        }
        if (TextUtils.isEmpty(etZixunNeirong.getText().toString().trim())) {
            showToast("请输入咨询内容");
            return;
        }
        if (adapter.getFileList() != null && adapter.getFileList().size() > 0) {//有图片调用上传图片接口，图片全部上传完成后调用创建咨询接口
            for (File file : adapter.getFileList()) {
                sendPhotoToServer(file.getPath());
            }
        } else {//没有图片直接调用创建咨询接口
            saveQuestion();
        }
    }

    /**
     * 创建咨询
     */
    private void saveQuestion() {
        if (hasPosted) {
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("type", selectedIds);
        map.put("content", etZixunNeirong.getText().toString().trim());
        map.put("img", img);//上传图片半路径，以逗号隔开

        //加个双重保险
        hasPosted = true;

        fromNetwork.saveQuestion(map)
                .compose(new RxActivityHelper<CommonReturn>().ioMain(ZiXunAddActivity.this, true))
                .subscribe(new MySubscribe<CommonReturn>(mContext, true) {
                    @Override
                    protected void success(CommonReturn resultBean) {
                        hasPosted = true;
                        //tangkun 发出通知 刷新首页最新列表？
                        EventBus.getDefault().post(true, "ZiXunFragment.refresh");
                        showToast("创建成功");
                        Utils.hideSoftKeyboard(ZiXunAddActivity.this, back);
                        JumpHelper.finish(mContext);
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        hasPosted = false;
                        showToast(errorMessage);
                    }
                });
    }


    /**
     * 上传图片到服务器
     *
     * @param filePath 本地图片路径
     */
    private synchronized void sendPhotoToServer(String filePath) {
        String[] filePathArray = filePath.split("/");
        //文件名
        String fileName = filePathArray[filePathArray.length - 1];
        fileName = fileName + ".png";//加上.png后缀名
        LogUtils.e("文件名称：" + fileName);
        //生成文件
        File file = new File(filePath);
        //组装partMap对象
        Map<String, RequestBody> partMap = new HashMap<>();
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);//文件
//        partMap.put("file", fileBody);//文件名
        partMap.put("file\"; filename=\"" + fileName + "", fileBody);//文件名
//        RequestBody dirBody = RequestBody.create(MediaType.parse("text/plain"), "user/header");//dir参数值
//        RequestBody fileNameBody = RequestBody.create(MediaType.parse("text/plain"), fileName);//文件名参数值
//        partMap.put("dir", dirBody);//dir参数
//        partMap.put("fileName", fileNameBody);//dir参数
        fromNetwork.uploadImageQuestion(partMap).compose(new RxActivityHelper<UploadResourceReturn>().ioMain(ZiXunAddActivity.this, true))
                .subscribe(new MySubscribe<UploadResourceReturn>(mContext, true) {
                    @Override
                    protected void success(UploadResourceReturn uploadResourceReturn) {
                        if (uploadResourceReturn.data != null) {
                            if (uploadResourceReturn.data.size() > 0) {
                                //文件上传成功，返回的图片半路径，拼接成图片集合
                                if (TextUtils.isEmpty(img)) {
                                    img = uploadResourceReturn.data.get(0).url;
                                } else {
                                    img = img + "," + uploadResourceReturn.data.get(0).url;
                                }
                                //图片全部上传完成，调用创建咨询接口
                                if (img.split(",").length == adapter.getFileList().size()) {
                                    saveQuestion();
                                }
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //修改了咨询分类
        if (resultCode == RESULT_OK) {
            selectedIds = data.getStringExtra("id");
            selectedName = data.getStringExtra("name");
            //设置咨询分类名称
            tvZixunFenlei.setText(TextUtils.isEmpty(selectedName) ? "" : selectedName);
        }

        // 刷新来自相册列表选中的图片列表
        if (requestCode == ImageFileAdapter.REQUEST_CODE_CAPTURE_IMAGE && resultCode == CaptureImageActivity.CAPTURE) {
            List<File> list = (List<File>) data.getSerializableExtra("fileList");
            if (list != null) {
                adapter.getFileList().addAll(list);
                adapter.notifyDataSetChanged();
                Utils.setGridViewHeightBasedOnChildren(squareGridView, 3);
            }
        }

        // 刷新有过删除后的图片列表
        if (requestCode == ImageFileAdapter.REQUEST_CODE_CAPTURE_IMAGE && resultCode == DeleteImageActivity.RESULT_CODE_DELETE_CHANGED) {
            List<File> fileList = new ArrayList<File>();
            fileList = (List<File>) data.getSerializableExtra("fileList");
            if (fileList != null) {
                adapter.setFileList(fileList);
            }
            Utils.setGridViewHeightBasedOnChildren(squareGridView, 3);
            adapter.notifyDataSetChanged();
        }
    }
}
